#include "listen_thread.h"
#include <QTextStream>
#include "tb_interface/tb_interface.h"
listen_thread::listen_thread(const TASKBUS::cmdlineParser * cmdline,bool taskBusMod ,QObject * parent)
	:QThread(parent)
	,m_bTBInterface(taskBusMod)
	,m_cmdline(cmdline)
{

}
void listen_thread::run()
{
	if (!m_bTBInterface)
	{
		QTextStream st_in(stdin);
		while (!st_in.atEnd())
		{
			QString line = st_in.readLine();
			if (line.indexOf("destin=")>=0)
			{
				emit newCmd(line);
			}
		}
	}
	else
	{
		using namespace TASKBUS;
		bool bfinished = false;
		const unsigned int sub_in = m_cmdline->toInt("cmd_in",0);
		while (false==bfinished)
		{
			subject_package_header header;
			std::vector<unsigned char> packagedta = pull_subject(&header);
			if (!is_valid_header(header))
			{
				fprintf(stderr,"Recived BAD Command.");
				fflush(stderr);
				continue;
			}
			if (!packagedta.empty())
			{
				if ( is_control_subject(header))
				{
					//收到命令进程退出的广播消息,退出
					if (strstr((const char *)packagedta.data(),"function=quit;")!=nullptr)
					{
						fprintf(stderr,"Recived Quit Command.");
						fflush(stderr);
						bfinished = true;
					}
				}
				else if (header.subject_id==sub_in && sub_in>0)
				{
					//豆包生成的代码，审计人：丁劲犇
					static QByteArray leftoverData;
					// 拼接上次遗留的数据
					leftoverData.append((const char *)packagedta.data(),packagedta.size());
					// 按换行符分割数据
					int start = 0;
					int pos = leftoverData.indexOf('\n', start);
					while (pos != -1) {
						// 提取一行数据（包含到换行符）
						QByteArray lineData = leftoverData.mid(start, pos - start + 1);
						// 移除换行符并转换为UTF-8字符串
						QString line = QString::fromUtf8(lineData).trimmed();
						if (!line.isEmpty()) {
							emit newCmd(line);
						}
						// 移动到下一行的起始位置
						start = pos + 1;
						pos = leftoverData.indexOf('\n', start);
					}
					// 保存未处理完的部分（不完整的行）
					leftoverData = leftoverData.mid(start);
				}
			}
		}
	}
	emit quit_app();
}
